package com.quasar.hpatient.view.personal.collection;

import android.graphics.Rect;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.malinskiy.superrecyclerview.OnMoreListener;
import com.malinskiy.superrecyclerview.SuperRecyclerView;
import com.quasar.hpatient.R;
import com.quasar.hpatient.base.BaseFragment;
import com.quasar.hpatient.choicePhoto.CommonUtils;
import com.quasar.hpatient.constant.ConstantManger;
import com.quasar.hpatient.model.event.UpdateEvent;
import com.quasar.hpatient.model.httpmodel.AnotherResult;
import com.quasar.hpatient.model.medicalmodel.CommunityData;
import com.quasar.hpatient.onInterface.CircleContract;
import com.quasar.hpatient.presenter.CirclePresenter;
import com.quasar.hpatient.view.community.CircleAdapter;
import com.quasar.hpatient.view.community.CommentListView;
import com.quasar.hpatient.view.community.DivItemDecoration;
import com.quasar.hpatient.view.community.bean.CommentConfig;
import com.quasar.hpatient.view.community.bean.CommentItem;
import com.quasar.hpatient.view.community.bean.FavortItem;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * author : 许建宏
 * Date: 2017/12/5 0005
 * View:社区
 */

@EFragment(R.layout.friends_circle_layout)
public class FriendsCircleFragment extends BaseFragment implements  CircleContract.View {


    private CirclePresenter presenter;
    private LinearLayoutManager layoutManager;
    private SwipeRefreshLayout.OnRefreshListener refreshListener;
    private final static int TYPE_PULLREFRESH = 1;
    private final static int TYPE_UPLOADREFRESH = 2;
    private CircleAdapter circleAdapter;
    private CommunityData.ListCommentBean commentConfig;
    private int currentKeyboardH;
    private int screenHeight;
    private int editTextBodyHeight;
    private int selectCircleItemH;
    private int selectCommentItemOffset;

    @ViewById(R.id.recyclerView)
    SuperRecyclerView recyclerView;
    @ViewById(R.id.bodyLayout)
    RelativeLayout bodyLayout;
    @ViewById(R.id.editTextBodyLl)
    LinearLayout edittextbody;
    @ViewById(R.id.circleEt)
    EditText editText;
    @ViewById(R.id.sendIv)
    ImageView sendIv;

    @AfterViews
    void init() {
        initView();

        //实现自动下拉刷新功能
        recyclerView.getSwipeToRefresh().post(new Runnable(){
            @Override
            public void run() {
                recyclerView.setRefreshing(true);//执行下拉刷新的动画
                refreshListener.onRefresh();//执行数据加载操作
            }
        });

        initData();
    }

    public void loadData(){
        recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (edittextbody.getVisibility() == View.VISIBLE) {
                    updateEditTextBodyVisible(View.GONE, null);
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    public void initView() {
        presenter = new CirclePresenter(this);
        layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DivItemDecoration(2, true));
        recyclerView.getMoreProgressView().getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT;

        loadData();

        refreshListener = new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        presenter.loadData(TYPE_PULLREFRESH);
                    }
                }, 2000);
            }
        };

        recyclerView.setRefreshListener(refreshListener);
        recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    Glide.with(getActivity()).resumeRequests();
                } else {
                    Glide.with(getActivity()).pauseRequests();
                }

            }
        });

        circleAdapter = new CircleAdapter(getActivity());
        circleAdapter.setCirclePresenter(presenter);
        recyclerView.setAdapter(circleAdapter);

        sendIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (presenter != null) {
                    //发布评论
                    String content =  editText.getText().toString().trim();
                    if(TextUtils.isEmpty(content)){
                        Toast.makeText(getActivity(), "评论内容不能为空...", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    presenter.addComment(content, commentConfig);
                }
                updateEditTextBodyVisible(View.GONE, null);
            }
        });

        setViewTreeObserver();

    }


    private void setViewTreeObserver() {
        final ViewTreeObserver swipeRefreshLayoutVTO = bodyLayout.getViewTreeObserver();
        swipeRefreshLayoutVTO.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                Rect r = new Rect();
                bodyLayout.getWindowVisibleDisplayFrame(r);
                int statusBarH =  getStatusBarHeight();//状态栏高度
                int screenH = bodyLayout.getRootView().getHeight();
                if(r.top != statusBarH ){
                    //在这个demo中r.top代表的是状态栏高度，在沉浸式状态栏时r.top＝0，通过getStatusBarHeight获取状态栏高度
                    r.top = statusBarH;
                }
                int keyboardH = screenH - (r.bottom - r.top);

                if(keyboardH == currentKeyboardH){//有变化时才处理，否则会陷入死循环
                    return;
                }

                currentKeyboardH = keyboardH;
                screenHeight = screenH;//应用屏幕的高度
                editTextBodyHeight = edittextbody.getHeight();

//                if(keyboardH<150){//说明是隐藏键盘的情况
//                    updateEditTextBodyVisible(View.GONE, null);
//                    return;
//                }
                //偏移listview
//                if(layoutManager!=null && commentConfig != null){
//                    layoutManager.scrollToPositionWithOffset(commentConfig.circlePosition + CircleAdapter.HEADVIEW_SIZE, getListviewOffset(commentConfig));
//                }
            }
        });
    }

    /**
     * 获取状态栏高度
     * @return
     */
    private int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }


    private void measureCircleItemHighAndCommentItemOffset(CommunityData.ListCommentBean commentConfig){
        if(commentConfig == null)
            return;

        int firstPosition = layoutManager.findFirstVisibleItemPosition();
        //只能返回当前可见区域（列表可滚动）的子项//commentConfig.circlePosition +
        View selectCircleItem = layoutManager.getChildAt( CircleAdapter.HEADVIEW_SIZE - firstPosition);

        if(selectCircleItem != null){
            selectCircleItemH = selectCircleItem.getHeight();
        }

//        if(commentConfig.commentType == CommentConfig.Type.REPLY){
//            //回复评论的情况
//            CommentListView commentLv = (CommentListView) selectCircleItem.findViewById(R.id.commentList);
//            if(commentLv!=null){
//                //找到要回复的评论view,计算出该view距离所属动态底部的距离
//                View selectCommentItem = commentLv.getChildAt(commentConfig.commentPosition);
//                if(selectCommentItem != null){
//                    //选择的commentItem距选择的CircleItem底部的距离
//                    selectCommentItemOffset = 0;
//                    View parentView = selectCommentItem;
//                    do {
//                        int subItemBottom = parentView.getBottom();
//                        parentView = (View) parentView.getParent();
//                        if(parentView != null){
//                            selectCommentItemOffset += (parentView.getHeight() - subItemBottom);
//                        }
//                    } while (parentView != null && parentView != selectCircleItem);
//                }
//            }
//        }
    }

    /**
     * 测量偏移量
     * @param commentConfig
     * @return
     */
    private int getListviewOffset(CommentConfig commentConfig) {
        if(commentConfig == null)
            return 0;
        //这里如果你的listview上面还有其它占高度的控件，则需要减去该控件高度，listview的headview除外。
        //int listviewOffset = mScreenHeight - mSelectCircleItemH - mCurrentKeyboardH - mEditTextBodyHeight;
        int listviewOffset = screenHeight - selectCircleItemH - currentKeyboardH - editTextBodyHeight;
        if(commentConfig.commentType == CommentConfig.Type.REPLY){
            //回复评论的情况
            listviewOffset = listviewOffset + selectCommentItemOffset;
        }
        return listviewOffset;
    }

    @Override
    public void initData() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void showLoading(String msg) {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showError(String errorMsg) {

    }

    @Override
    public void update2DeleteCircle(String circleId) {

    }

    @Override
    public void update2AddFavorite(int circlePosition, FavortItem addItem) {

    }

    @Override
    public void update2DeleteFavort(int circlePosition, String favortId) {

    }

    @Override
    public void update2AddComment(int circlePosition, CommunityData.ListCommentBean addItem) {

        if (addItem != null) {
            CommunityData item = (CommunityData) circleAdapter.getDatas().get(circlePosition);
            item.getListComment().add(addItem);
            circleAdapter.notifyDataSetChanged();
            //circleAdapter.notifyItemChanged(circlePosition+1);
        }
        //清空评论文本
        editText.setText("");
    }

    @Override
    public void update2DeleteComment(int circlePosition, String commentId) {

    }

    //点击评论
    @Override
    public void updateEditTextBodyVisible(int visibility, CommunityData.ListCommentBean commentConfig) {
        this.commentConfig = commentConfig;
        edittextbody.setVisibility(visibility);
        measureCircleItemHighAndCommentItemOffset(commentConfig);
        if(View.VISIBLE==visibility){
            editText.requestFocus();
            //弹出键盘
            CommonUtils.showSoftInput( editText.getContext(),  editText);

        }else if(View.GONE==visibility){
            //隐藏键盘
            CommonUtils.hideSoftInput( editText.getContext(),  editText);
        }
    }

    @Override
    public void update2loadData(int loadType, AnotherResult<CommunityData> data) {
        if (loadType == TYPE_PULLREFRESH){
            recyclerView.setRefreshing(false);
            circleAdapter.setDatas(data.getList());
        }else if(loadType == TYPE_UPLOADREFRESH){
            circleAdapter.getDatas().addAll(data.getList());
        }
        circleAdapter.notifyDataSetChanged();

        if(circleAdapter.getDatas().size()<45 + CircleAdapter.HEADVIEW_SIZE){
            recyclerView.setupMoreListener(new OnMoreListener() {
                @Override
                public void onMoreAsked(int overallItemsCount, int itemsBeforeMore, int maxLastVisiblePosition) {

                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            presenter.loadData(TYPE_UPLOADREFRESH);
                        }
                    }, 2000);

                }
            }, 1);
        }else{
            recyclerView.removeMoreListener();
            recyclerView.hideMoreProgress();
        }
    }

    //加载失败回调
    @Override
    public void onError(String msg) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(presenter !=null){
            presenter.recycle();
        }
        EventBus.getDefault().unregister(this);
    }


    //刷新界面
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(UpdateEvent updateEvent) {
        if (updateEvent.type.equals(ConstantManger.UPDATEPOST)) {
            loadData();
        }
    }
}
